package com.hustzp.com.xichuangzhu.poetry;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.LeadingMarginSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.custom.vg.list.CustomAdapter;
import com.custom.vg.list.CustomListView;
import com.custom.vg.list.OnItemClickListener;
import com.hustzp.com.xichuangzhu.R;
import com.hustzp.com.xichuangzhu.XCZBaseFragmentActivity;
import com.hustzp.com.xichuangzhu.fragment.DayFragment;
import com.hustzp.com.xichuangzhu.login.LoginActivity;
import com.hustzp.com.xichuangzhu.model.Collections;
import com.hustzp.com.xichuangzhu.model.Review;
import com.hustzp.com.xichuangzhu.poetry.adapter.CollectionWorkCatagoryAdapter;
import com.hustzp.com.xichuangzhu.poetry.adapter.CollectionWorkQuotesAdapter;
import com.hustzp.com.xichuangzhu.poetry.dao.CollectionKindListDao;
import com.hustzp.com.xichuangzhu.poetry.model.CollectionWorks;
import com.hustzp.com.xichuangzhu.poetry.model.Works;
import com.hustzp.com.xichuangzhu.utils.ScreenshotUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Copyright (C) 2015 The huimai mobile client Project
 * All right reserved.
 *
 * @author: wuzhimin@huimai365.com
 * @date: 2016/5/29 0:18
 * @Description:诗词 作品页
 */
public class PoetryDetailAct extends XCZBaseFragmentActivity implements OnItemClickListener {
    private List<CollectionWorks> collectionKindses;
    private TextView tv_back;
    private ImageButton img_author;
    private ImageButton img_baike;
    private ImageButton img_menu;

    private ScrollView mScrollView;

    private LinearLayout worksShotPng;
    private TextView tv_intro_title;
    private TextView tv_category_title;
    private TextView tv_quote_title;
    private ImageButton img_collection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poetry);
        tv_back = (TextView) findViewById(R.id.tv_back);
        img_author = (ImageButton) findViewById(R.id.img_author);
        img_baike = (ImageButton) findViewById(R.id.img_baike);
        img_menu = (ImageButton) findViewById(R.id.img_menu);
        img_collection = (ImageButton) findViewById(R.id.img_collection);
        tv_intro_title = (TextView) findViewById(R.id.tv_intro_title);
        tv_category_title = (TextView) findViewById(R.id.tv_category_title);
        tv_quote_title = (TextView) findViewById(R.id.tv_quote_title);
        Works works = (Works) getIntent().getSerializableExtra(Works.class.getSimpleName());

        mScrollView = (ScrollView) findViewById(R.id.scroll_view);
        worksShotPng = (LinearLayout) findViewById(R.id.woks_shot_layout);

        findViewById(R.id.rlytBackBg).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initActionBar(works);
        showData(works);
    }

    @Override
    protected void onResume() {
        loadCollection();
        super.onResume();
    }

    /**
     * 加载收藏未收藏
     */
    private void loadCollection() {
        //没登录,不显示收藏按钮
        if (AVUser.getCurrentUser() == null) {
            return;
        }
        AVObject user = AVObject.createWithoutData("objectId", AVUser.getCurrentUser().getObjectId());
        Works works = (Works) getIntent().getSerializableExtra(Works.class.getSimpleName());
        AVQuery<AVObject> query1 = new AVQuery<>("LikeWork");
        query1.whereEqualTo("user", user);

        AVQuery<AVObject> query2 = new AVQuery<>("LikeWork");
        query2.whereEqualTo("workId", Integer.valueOf(works.getId()));

        AVQuery<AVObject> query = AVQuery.and(Arrays.asList(query1, query2));

        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (list != null && !list.isEmpty()) {
                    img_collection.setTag(list.get(0));
                    img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.frag_review_head_collection_pressed));
                } else {
                    img_collection.setTag(null);
                    img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.frag_review_head_collection_default));
                }
            }
        });
    }

    public void addCollection(View v) {
        if (AVUser.getCurrentUser() == null) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
            //跳转登录
        }
        AVObject object = (AVObject) img_collection.getTag();
        if (object != null) {
            //已收藏,删除收藏
            // 执行 CQL 语句实现删除一个
            object.deleteInBackground(new DeleteCallback() {
                @Override
                public void done(AVException e) {
                    if (e == null) {
                        img_collection.setTag(null);
                        //删除成功
                        img_collection.setImageDrawable(getResources().getDrawable(R.mipmap.frag_review_head_collection_default));
                    }
                }
            });
        } else {
            //未收藏,添加到收藏
            Works works = (Works) getIntent().getSerializableExtra(Works.class.getSimpleName());
            final AVObject todo = new AVObject("LikeWork");
            todo.put("user", AVUser.getCurrentUser());
            todo.put("workId", Integer.valueOf(works.getId()));
            todo.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    if (e == null) {
                        // 收藏成功
                        loadCollection();
                    } else {
                        // 失败的话，请检查网络环境以及 SDK 配置是否正确
                    }
                }
            });
        }
    }


    private void initActionBar(Works works) {
        String from = getIntent().getStringExtra("from");
        if (DayFragment.class.getSimpleName().equals(from)) {
            tv_back.setText(getResources().getText(R.string.one_day_rewar));
            img_baike.setVisibility(View.VISIBLE);
            img_author.setVisibility(View.GONE);
        } else if (PoetryAuthorAct.class.getSimpleName().equals(from)) {
            tv_back.setText("" + works.getAuthor());
            img_baike.setVisibility(View.VISIBLE);
            img_author.setVisibility(View.GONE);
        } else {
            tv_back.setText("返回");
            img_baike.setVisibility(View.VISIBLE);
            img_author.setVisibility(View.GONE);
        }
    }

    public void showAuthor(View v) {
        Works works = (Works) v.getTag();
        Intent intent = new Intent(this, PoetryAuthorAct.class);
        intent.putExtra(Works.class.getSimpleName(), works);
        startActivity(intent);
    }

    public void openBaike(View v) {
        Works works = (Works) v.getTag();
        openBaike(works.getBaidu_wiki());
    }

    public void openMenu(View v) {
        final Works works = (Works) v.getTag();
        List<String> menus = new ArrayList<>();
        menus.add("分享");
        menus.add("保存为图片");
        menus.add("勘误");
        menus.add("「" + works.getAuthor() + "」");

        initSharePopupWindow();
        showSharePopupWindow(menus, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
                    case 0:
                        screenShotView = worksShotPng;
                        isAdd = true;
                        showSharePopupWindow();
                        break;
                    case 1:
                        hideAlert();
                        ScreenshotUtil.saveBitmapView(PoetryDetailAct.this, worksShotPng, true);
                        break;
                    case 2: // 勘误页面
                        hideAlert();
                        Intent errtaIntent = new Intent(PoetryDetailAct.this, WorkErrataListActivity.class);
                        errtaIntent.putExtra("workId", Integer.valueOf(works.getId()));
                        startActivity(errtaIntent);
                        break;
                    case 3:
                        hideAlert();
                        Intent intent = new Intent(getApplicationContext(), PoetryAuthorAct.class);
                        intent.putExtra(Works.class.getSimpleName(), works);
                        startActivity(intent);
                        break;
                }
            }
        });

    }

    private void showData(Works works) {
        TextView tv_work_title = (TextView) findViewById(R.id.tv_work_title);
        TextView tv_dynasty = (TextView) findViewById(R.id.tv_dynasty);
        TextView tv_author = (TextView) findViewById(R.id.tv_author);
        TextView tv_work_content = (TextView) findViewById(R.id.tv_work_content);
        TextView tv_intro = (TextView) findViewById(R.id.tv_intro);

        CollectionKindListDao dao = new CollectionKindListDao(this);
        Works workStyle = dao.getWorks(works);
        img_author.setTag(workStyle);
        tv_dynasty.setTag(workStyle);
        tv_author.setTag(workStyle);
        img_baike.setTag(workStyle);
        img_menu.setTag(workStyle);
        tv_work_title.setText(workStyle.getTitle());
        tv_dynasty.setText("[" + workStyle.getDynasty() + "]");
        tv_author.setText(workStyle.getAuthor());
        tv_work_content.setText(workStyle.getContent());
        if (TextUtils.isEmpty(workStyle.getIntro())) {
            tv_intro_title.setVisibility(View.GONE);
            tv_intro.setVisibility(View.GONE);
        } else {
            tv_intro_title.setVisibility(View.VISIBLE);
            tv_intro.setVisibility(View.VISIBLE);
        }
        tv_intro.setText(workStyle.getIntro());
        //显示诗词样式
        if (workStyle != null && "indent".equals(workStyle.getLayout())) {
//            tv_work_content.setGravity(Gravity.NO_GRAVITY);
//            String content = workStyle.getContent().replaceAll("[\\n]", "  ");
            SpannableStringBuilder style = new SpannableStringBuilder(workStyle.getContent());//构建builder
            style.setSpan(new LeadingMarginSpan.Standard(96, 0), 0, style.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            tv_work_content.setText(style);//将SpannableString设置到TextView上
        } else if (workStyle != null && "center".equals(workStyle.getLayout())) {
            tv_work_content.setGravity(Gravity.CENTER);
        }
        CustomListView lvCatagory = (CustomListView) findViewById(R.id.lvCatagory);
        lvCatagory.setDividerHeight(20);
        lvCatagory.setDividerWidth(20);

        collectionKindses = dao.getCollectionWorksCatagory(works);
        if (collectionKindses == null || collectionKindses.isEmpty()) {
            tv_category_title.setVisibility(View.GONE);
        }
        CustomAdapter adapter = new CollectionWorkCatagoryAdapter(this, collectionKindses);
        lvCatagory.setAdapter(adapter);
        lvCatagory.setOnItemClickListener(this);

        ListView lvQuotes = (ListView) findViewById(R.id.lvQuotes);
        lvQuotes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Review review = (Review) parent.getAdapter().getItem(position);
                Intent intent = new Intent(PoetryDetailAct.this, QuotesAct.class);
                intent.putExtra(QuotesAct.class.getSimpleName(), review);
                startActivity(intent);
            }
        });
        List<Review> quotes = dao.getCollectionWorksQuotes(works);
        if (quotes == null || quotes.isEmpty()) {
            tv_quote_title.setVisibility(View.GONE);
        }
        BaseAdapter quotesAdapter = new CollectionWorkQuotesAdapter(this, quotes);
        lvQuotes.setAdapter(quotesAdapter);
    }

    public void onClose(View v) {
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        CollectionWorks works = collectionKindses.get(position);
        CollectionKindListDao dao = new CollectionKindListDao(this);
        Collections collections = dao.getCollections(works);
        Intent intent = new Intent(this, CatagoryListAct.class);
        intent.putExtra(Collections.class.getSimpleName(), collections);
        startActivity(intent);
    }
}
